package client

import (
	"fmt"
	"net"
	"reflect"

	"gitee.com/ksbb/go-server/util"
)

type Handler func()

type Register struct {
}
type Client interface {
	Conn()
}

type Opt map[string]Handler

var c Client

var defaultClient Client

func NewClient(ip string, port int, sType ...string) {
	if len(sType) != 0 && sType[0] == "UDP" {
		defaultClient = newTcpClient(ip, port)
	}

	defaultClient = newUdpClient(ip, port)
	fmt.Println(defaultClient)
}

//默认的服务器
func GetClient() Client {
	return defaultClient
}

//开始服务器
func Start() {
	//反射调用
	v := reflect.ValueOf(defaultClient)
	v.MethodByName("Conn").Call(nil)
}

func On(event string, f Handler) {
	c = GetClient()
	util.RegisterOpts(event, f)
}

//发送到用户台
func ToConsole(str string) {
	fmt.Println(str)
}

//发送到客户端
func Send(str string) {
	v := reflect.ValueOf(defaultClient)
	typev := v.Elem().FieldByName("Conns").Type().String()
	//fmt.Println(typev)
	var conn interface{}
	if typev == "*net.UDPConn" {
		conn = v.Elem().FieldByName("Conns").Interface().(*net.UDPConn)
		addr := v.Elem().FieldByName("Add").Interface().(*net.UDPAddr)
		v.MethodByName("Send").Call([]reflect.Value{
			reflect.ValueOf(conn),
			reflect.ValueOf(addr),
			reflect.ValueOf(str),
		})
	} else {
		conn = v.Elem().FieldByName("Conns").Interface().(net.Conn)
		v.MethodByName("Send").Call([]reflect.Value{
			reflect.ValueOf(conn),
			reflect.ValueOf(str),
		})
	}
	//fmt.Println(conn)
	////获取最新那条连接

}

//接受服务器信息
func Recv() {
	v := reflect.ValueOf(defaultClient)
	typev := reflect.ValueOf(defaultClient).Elem().FieldByName("Conns").Type().String()
	var conn interface{}
	if typev == "*net.UDPConn" {
		conn = v.Elem().FieldByName("Conns").Interface().(*net.UDPConn)
	} else {
		conn = v.Elem().FieldByName("Conns").Interface().(net.Conn)
	}

	//fmt.Println(conn)
	////获取最新那条连接
	v.MethodByName("Recv").Call([]reflect.Value{
		reflect.ValueOf(conn),
	})
}
func Do(e string) bool {
	opt, ok := util.OptsT[e] //看有没有注册发送方法
	if ok {
		opt()
		return true
	}
	return false
}
